package com.jlastu.dlxy_androidapp.view.main;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.jlastu.dlxy_androidapp.R;
import com.jlastu.dlxy_androidapp.contract.MineDetailsContract;
import com.jlastu.dlxy_androidapp.entity.Photo;
import com.jlastu.dlxy_androidapp.entity.User;
import com.jlastu.dlxy_androidapp.presenter.MineDetailsPresenter;
import com.jlastu.dlxy_androidapp.utils.SpUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;

public class MineDetailsActivity extends AppCompatActivity implements View.OnClickListener, MineDetailsContract.IMineDetailsView {
    private MineDetailsContract.IMineDetailsPresenter mMineDetailsPresenter;
    private ImageView mBack;

    private ImageView mMineHead;
    private TextView mAddName;
    private TextView mAddPhone;
    private TextView mAddAge;

    private TextView mMineName;
    private TextView mMinePhone;
    private TextView mMineAge;

    private SpUtils mSpUtils;
    private int user_id;
    private User mUser;
    @Override
    public void onConfigurationChanged(android.content.res.Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        // 检查屏幕方向是否为横屏
        if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
            Log.d("Orientation", "Landscape detected");

            // 创建并启动新的Activity
            Intent intent = new Intent(this, LandscapeActivity.class);
            startActivity(intent);

            // 可选：关闭当前Activity
            finish();
        }
    }


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_mine_details);
        mMineDetailsPresenter = new MineDetailsPresenter(this, this);

        mBack = findViewById(R.id.back_button);
        mBack.setOnClickListener(this);
        mMineHead = findViewById(R.id.mine_head);
        mMineHead.setOnClickListener(this);
//        添加按钮
        mAddName = findViewById(R.id.add_username);
        mAddName.setOnClickListener(this);
        mAddPhone = findViewById(R.id.add_phone);
        mAddPhone.setOnClickListener(this);
        mAddAge = findViewById(R.id.add_age);
        mAddAge.setOnClickListener(this);

//        信息显示
        mMineName = findViewById(R.id.username);

        mMinePhone = findViewById(R.id.phone);

        mMineAge = findViewById(R.id.age);

        mSpUtils = new SpUtils(getApplicationContext());
        user_id = mSpUtils.getInt("userid", 0);


    }

    @Override
    public void onResume() {
        super.onResume();
        mMineDetailsPresenter.getUser(user_id);
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.back_button) {
            onBackPressed();
            finish();
        }
        else if (id == R.id.mine_head) {
            openImageChooser();
        }
        else if (id == R.id.add_username) {
            String fieldName = "用户名";
            showInputDialog(mMineName, fieldName);
        }
        else if (id == R.id.add_phone) {
            String fieldName = "电话";
            showInputDialog(mMinePhone, fieldName);
        }
        else if (id == R.id.add_age) {
            String fieldName = "年龄";
            showInputDialog(mMineAge, fieldName);
        }
    }

    private void openImageChooser() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "选择图片"), 1);
    }




    private void showInputDialog(final TextView textView, final String fieldName) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("输入新的" + fieldName);

        final EditText input = new EditText(this);
        input.setInputType(InputType.TYPE_CLASS_TEXT);
        input.setText(textView.getText().toString());
        builder.setView(input);

        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                textView.setText(input.getText().toString());
                updateUser();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

        builder.show();
    }

    private void updateUser() {
        //调用更改方法
        mUser.setUserName(mMineName.getText().toString());
        mUser.setUserPhone(mMinePhone.getText().toString());
        mUser.setUserAge(mMineAge.getText().toString());
        mMineDetailsPresenter.updateUser(user_id, mUser);

    }

    @Override
    public void showUser(User user) {
        mUser = user;
        Log.d("TAG", "showUser: " + Arrays.toString(user.getData()));
        byte[] byteArray;
        if (user != null && user.getData() != null) {
            byteArray = user.getData();
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            mMineHead.setImageBitmap(bitmap);
        }else {
            //没有查到图片显示默认图片
            mMineHead.setImageResource(R.mipmap.ic_launcher);
        }
        //username
        if (user != null) {
            mMineName.setText(user.getUserName());
        }
        //phone
        if (user != null) {
            mMinePhone.setText(user.getUserPhone());
        }
        //age
        if (user != null) {
            mMineAge.setText(user.getUserAge());
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK && data != null && data.getData() != null) {
            Uri selectedImageUri = data.getData();
            try {
                Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                User photo = new User();
                photo.setBitmap(bitmap);
                Bitmap resized = Bitmap.createScaledBitmap(bitmap, (int) (bitmap.getWidth() * 0.3), (int) (bitmap.getHeight() * 0.3), true);
                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                resized.compress(Bitmap.CompressFormat.JPEG, 100, outputStream);
                mUser.setData(outputStream.toByteArray());
                mMineHead.setImageBitmap(mUser.getBitmap());
                updateUser();
            } catch (IOException e) {
                e.printStackTrace();
                Toast.makeText(this, "图片处理失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
